<template>
  <div class="device-search-list">
    <DynamicForm ref="dynamicTableRef" @click="callBack" :rulesForm="rulesForm" :refresh="state.refresh" type="search"/>
    <DynamicTable ref="dynamicTableRef" @click="callBack" :columns="columns" :table="state.table" :data="state.data"/>
  </div>
</template>

<script lang="ts" setup>
import {ref, h, defineProps, onMounted, reactive, nextTick, defineEmits} from 'vue'

import DynamicForm from '@/components/layout/form/dynamic-form.vue'
import DynamicTable from '@/components/layout/table/dynamic-table.vue'

import {searchColumns} from '@/assets/script/monitor/columns/device'
import {searchForm} from "@/assets/script/monitor/forms/device/device-search-form";
import {listDevicePageApi} from '@/api/device';
import {ElMessageBox, ElMessage} from "element-plus";

const dynamicFormRef = ref(DynamicForm)
const dynamicTableRef = ref(DynamicTable)

const columns = searchColumns
const rulesForm = searchForm

const emits = defineEmits<{ (e: 'click', data: object): void }>();

const state = reactive({
  columns: [] as any,
  forms: [] as any,
  data: [] as any,
  refresh: null as any,
  type: 'search',
  table: {
    total: 0,
    pageSize: 15,
    pageIndex: 1
  }
})

const props = defineProps({
  deviceType: null as any,
})

onMounted(() => {
  nextTick(() => {
    listDevicePage(props.deviceType)
  })
})

const listDevicePage = (deviceType: string) => {
  listDevicePageApi({constCode: deviceType}).then((data: any) => {
    if (data.code === 0) {
      state.data = data.data
      state.table.total = data.total
    }
  })
}

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'choice':
    case 'dblclick':
      // eslint-disable-next-line no-case-declarations
      const item = data.data
      if (item.bindStatus === 1) {
        ElMessageBox({
          title: '提示',
          message: '该设备已绑定、是否确认！',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              emits('click', {type: 'choice', value: props.deviceType, data: data.data})
            }
            done()
          },
        })
      } else {
        emits('click', {type: 'choice', value: props.deviceType, data: data.data})
      }
      break
    default:
      console.log('callBack', data)
      break
  }
}

</script>